<template>
  <div class="address-container">
    <el-card class="address-card">
      <template #header>
        <div class="card-header">
          <span>我的收货地址</span>
          <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
        </div>
      </template>
      
      <!-- 地址列表 -->
      <div class="address-list" v-if="!loading">
        <div v-if="addresses.length === 0" class="empty-address">
          <el-empty description="暂无收货地址，点击添加按钮新增"></el-empty>
        </div>
        
        <div v-else class="address-items">
          <div v-for="address in addresses" :key="address.id" class="address-item">
            <el-card :bordered="true" class="address-item-card">
              <div class="address-info">
                <div class="address-header">
                  <span class="name">{{ address.consignee_name }}</span>
                  <span class="phone">{{ address.phone_number }}</span>
                  <el-tag v-if="address.is_default" type="primary" size="small">默认</el-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }} {{ address.district }} {{ address.street_address }}
                </div>
                <div class="address-actions">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleEditAddress(address)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDeleteAddress(address.id)"
                  >
                    删除
                  </el-button>
                  <el-button
                    v-if="!address.is_default"
                    type="text"
                    size="small"
                    @click="handleSetDefault(address.id)"
                  >
                    设为默认
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
      
      <div v-else class="loading">
        <el-loading-spinner></el-loading-spinner>
        <div>加载中...</div>
      </div>
    </el-card>
    
    <!-- 地址表单对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="addressDialogTitle"
      width="600px"
    >
      <el-form ref="addressFormRef" :model="addressForm" :rules="rules">
        <el-form-item label="收货人" prop="consignee_name">
          <el-input v-model="addressForm.consignee_name"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model="addressForm.phone_number"></el-input>
        </el-form-item>
        
        <el-form-item label="所在地区" prop="province">
          <el-cascader
            v-model="addressRegion"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择省/市/区"
            @change="handleRegionChange"
          ></el-cascader>
        </el-form-item>
        
        <el-form-item label="详细地址" prop="street_address">
          <el-input
            v-model="addressForm.street_address"
            type="textarea"
            placeholder="请输入详细地址信息"
            :rows="2"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="addressForm.is_default">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddress">取消</el-button>
          <el-button type="primary" @click="submitAddress" :loading="addressSubmitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '../api'

// 地址列表数据
const addresses = ref([])
const loading = ref(false)

// 地址对话框相关
const addressDialogVisible = ref(false)
const addressDialogTitle = ref('新增地址')
const currentAddressId = ref(null)
const addressForm = reactive({
  consignee_name: '',
  phone_number: '',
  province: '',
  city: '',
  district: '',
  street_address: '',
  is_default: false
})
const addressRegion = ref([])
const addressFormRef = ref(null)
const addressSubmitting = ref(false)

// 地区选项（简化版，实际项目中可以使用完整的地区数据）
const regionOptions = ref([
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' },
          { value: '朝阳区', label: '朝阳区' },
          { value: '海淀区', label: '海淀区' },
          { value: '丰台区', label: '丰台区' }
        ]
      }
    ]
  },
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' },
          { value: '长宁区', label: '长宁区' },
          { value: '静安区', label: '静安区' }
        ]
      }
    ]
  }
])

// 级联选择器配置
const cascaderProps = {
  expandTrigger: 'hover',
  label: 'label',
  value: 'value'
}

// 表单验证规则
const rules = {
  consignee_name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { max: 20, message: '收货人姓名长度不能超过20个字符', trigger: 'blur' }
  ],
  phone_number: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  street_address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 200, message: '详细地址长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取地址列表
const fetchAddresses = async () => {
  try {
    loading.value = true
    const response = await userApi.getUserAddresses()
    addresses.value = response.data
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 新增地址
const handleAddAddress = () => {
  addressDialogTitle.value = '新增地址'
  currentAddressId.value = null
  resetAddressForm()
  addressDialogVisible.value = true
}

// 编辑地址
const handleEditAddress = (address) => {
  addressDialogTitle.value = '编辑地址'
  currentAddressId.value = address.id
  
  // 填充表单数据
  addressForm.consignee_name = address.consignee_name
  addressForm.phone_number = address.phone_number
  addressForm.province = address.province
  addressForm.city = address.city
  addressForm.district = address.district
  addressForm.street_address = address.street_address
  addressForm.is_default = address.is_default
  
  // 设置级联选择器值
  addressRegion.value = [address.province, address.city, address.district]
  
  addressDialogVisible.value = true
}

// 删除地址
const handleDeleteAddress = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该地址吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userApi.deleteUserAddress(id)
    ElMessage.success('删除成功')
    // 重新获取地址列表
    fetchAddresses()
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除地址失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 设置默认地址
const handleSetDefault = async (id) => {
  try {
    // 先获取地址详情
    const response = await userApi.getUserAddressDetail(id)
    const addressData = response.data
    
    // 设置为默认地址
    addressData.is_default = true
    await userApi.updateUserAddress(id, addressData)
    
    ElMessage.success('设置成功')
    // 重新获取地址列表
    fetchAddresses()
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置失败，请稍后重试')
  }
}

// 地区选择变化
const handleRegionChange = (value) => {
  if (value && value.length === 3) {
    addressForm.province = value[0]
    addressForm.city = value[1]
    addressForm.district = value[2]
  }
}

// 提交地址表单
const submitAddress = async () => {
  try {
    addressFormRef.value.validate(async (valid) => {
      if (valid) {
        addressSubmitting.value = true
        try {
          if (currentAddressId.value) {
            // 更新地址
            await userApi.updateUserAddress(currentAddressId.value, addressForm)
            ElMessage.success('更新成功')
          } else {
            // 创建地址
            await userApi.createUserAddress(addressForm)
            ElMessage.success('添加成功')
          }
          
          // 关闭对话框
          addressDialogVisible.value = false
          // 重新获取地址列表
          fetchAddresses()
        } catch (error) {
          console.error('保存地址失败:', error)
          ElMessage.error('保存失败，请稍后重试')
        } finally {
          addressSubmitting.value = false
        }
      }
    })
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('保存失败，请稍后重试')
    addressSubmitting.value = false
  }
}

// 取消地址编辑
const cancelAddress = () => {
  addressDialogVisible.value = false
  resetAddressForm()
}

// 重置地址表单
const resetAddressForm = () => {
  addressForm.consignee_name = ''
  addressForm.phone_number = ''
  addressForm.province = ''
  addressForm.city = ''
  addressForm.district = ''
  addressForm.street_address = ''
  addressForm.is_default = false
  addressRegion.value = []
  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }
}

// 组件挂载时获取地址列表
onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped>
.address-container {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.address-card {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.address-list {
  padding: 20px 0;
}

.empty-address {
  padding: 40px 0;
  text-align: center;
}

.address-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-item {
  width: 100%;
}

.address-item-card {
  width: 100%;
}

.address-info {
  padding: 10px 0;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 10px;
}

.address-header .name {
  font-weight: bold;
}

.address-header .phone {
  color: #606266;
}

.address-detail {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 15px;
}

.address-actions {
  display: flex;
  gap: 10px;
}

.loading {
  padding: 40px 0;
  text-align: center;
}
</style>